<template>
<a-card class="common-card common-card-top flex">
  <Line class="chart"  :loading="loadingRef" :chartData="chartData" title="汇总统计" />
    <BasicTable @register="registerTable" :showIndexColumn="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column?.dataIndex === 'name'">
          <div v-if="specialCodeList.includes(record.code)">
            {{ record.name }}
          </div>
        </template>
      </template>
    </BasicTable>
  </a-card>
  <a-card class="common-card common-card-bottom" title="各系统总电量">
    <TotalTable ref="totalTableRef" :loading="loadingTotalTableRef"></TotalTable>
  </a-card>
</template>
<script setup>
import { ref, reactive, h } from 'vue'
import TotalTable from './totalTable.vue'
import Line from '@/components/Charts/Line/index.vue'
import { getAllReportSystemRatio, getAllReportSystem2, getEleTypeAllReportBuilding, } from '@/api/power/electricity/electricity.ts'
import { BasicTable, useTable } from '@/components/Table'
import dayjs, { Dayjs } from 'dayjs'
import { mapValues } from 'lodash-es'

const chartData = ref()
const specialCodeList = ['空调', '水处理', '气化']
const commonConfig = reactive({
  tableData: [],//汇总统计数据
})
const loadingTotalTableRef = ref(false)
const totalTableRef = ref()

defineOptions({ name: 'SummarySheetTab1' })

const [registerTable, { setLoading, setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  bordered: true,
  striped: true,
})


const renderRowSpan = (item, index, key) => {
  if (item && item.code && commonConfig.tableData && commonConfig.tableData.length > 0) {
    if (
      index > 0 &&
      commonConfig.tableData[index - 1][key] &&
      item[key] === commonConfig.tableData[index - 1][key]
    ) {
      return 0 // 返回0表示在有跨度的行中不需要渲染，如果不为0，会被跨度合并时挤出到其他列显示
    }
    const count = commonConfig.tableData.filter((e) => e[key] === item[key]).length

    return count // 返回需要合并的跨度
  }
}

const formatHeader = (headerData) => {
  const headerList = [
    {
      title: '系统',
      dataIndex: 'code',
      width: 90,
      fixed: 'left',
      merge: true,
      customCell: (item, index) => {
        return {
          rowSpan: renderRowSpan(item, index, 'code'),
          colSpan: item.code === item.name ? 2 : 1,
        }
      },
    },
    {
      title: '子系统',
      dataIndex: 'name',
      width: 90,
      fixed: 'left',
      merge: true,
      customCell: (item, index) => {
        return {
          rowSpan: renderRowSpan(item, index, 'name'),
          colSpan: item.code === item.name ? 0 : 1
        }
      },
    },
    {
      title: '类别',
      dataIndex: 'type',
      width: 90,
      fixed: 'left',
    },
  ]

  if (headerData && headerData.length) {
    headerData.forEach((item, index) => {
      headerList.push({
        title: `${dayjs(item).format('D')}`,
        dataIndex: index,
        width: 80,
        customRender: ({ text, record: { type } }) => {
          if (typeof text === 'number') {
            if (type === '变化幅度') {
              const className = text > 0 ? 'red-text' : 'normal'
              return h('span', { class: className }, (text * 100).toFixed(2) + '%')
            }
            return text
          } else {
            return text || '--'
          }
        },
      })
    })
  }
  setColumns(headerList)
}

const formatTableData = (subitemData = []) => {
  let newData = []
  if (subitemData && subitemData.length > 0) {
    subitemData.forEach((item) => {
      if (item.data.length > 0) {
        let commonItem = {
          code: item.code,
          name: item.name,
        }
        const currentItem = [{
          ...commonItem,
          type: '用电量',
          ...mapValues(item.data, (data, index) => data
          ),
        },
        {
          ...commonItem,
          type: '变化幅度',
          ...mapValues(item.ratio, (data, index) => data
          ),
        }]
        newData = newData.concat(currentItem)
      }
    })
  }
  return newData
}

const getTotalData = async (searchParams) => {
  setLoading(true)
  await getAllReportSystem2({
    ...searchParams
  })
    .then((e) => {
      chartData.value = e
      formatHeader(e.xaxisList)
      let data = formatTableData(e.yaxisList)
      commonConfig.tableData = data
      setTableData(data)
    })
    .catch((e) => {
      setLoading(true)
    })
    .finally(() => {
      setLoading(false)
    })
}

const getReportSystemData = async (searchParams) => {
  loadingTotalTableRef.value = true
  await getAllReportSystemRatio({
    ...searchParams
  })
    .then((e) => {
      totalTableRef.value.setData(e)
    })
    .catch((e) => {
      loadingTotalTableRef.value = true
    })
    .finally(() => {
      loadingTotalTableRef.value = false
    })
}

const getData = (searchParams) => {
  getReportSystemData(searchParams)
  getTotalData(searchParams)
}

defineExpose({
  getData
})

</script>

<style scoped
  lang="scss">
  :deep(.red-text) {
    color: red;
  }
</style>
